//
//  KXMeViewController.swift
//  KXBook
//
//  Created by  on 2022/9/7.
//

import UIKit

class KXMeViewController: KXViewController {
    @IBOutlet var avatar: UIImageView!
    @IBOutlet var tableView: UITableView!
    @IBOutlet var bgTop: UIView!
    @IBOutlet var name: UILabel!
    @IBOutlet var bgView: UIView!
    @IBOutlet var bgViewH: NSLayoutConstraint!
    var array = [[String:String]]()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.avatar.image = UIImage(named: "头像")
        UIImage.withURL(APP.user.headImg , { img in
            if APP.user.id != "去登录"{
                self.avatar.image = img
            }
        })
        self.name.text = APP.user.username
        self.array = [["img":"组 75","title":"类别管理"],["img":"组 74","title":"隐私政策"],["img":"组 73","title":"账号管理"]]
        self.backBtn?.isHidden = true
        self.bgViewH.constant = CGFloat(self.array.count * 65)
        self.tableView.register(KXMeCell.nib(), forCellReuseIdentifier: KXMeCell.ID())
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.setupNaviBarColor("#E27BC1".color(), .black)
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.setupNaviBarColor(.white, .black)
    }
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        self.bgView.layer.masksToBounds = false
        self.bgView.layer.shadowColor = "#9B9B9B".color().cgColor
        self.bgView.layer.shadowOffset = CGSize(width:0, height:3)
        self.bgView.layer.shadowRadius = 10
        self.bgView.layer.cornerRadius = 10
        self.bgView.layer.shadowOpacity = 1
        
        let layer = CAShapeLayer()
        let path = UIBezierPath()
        let h = self.bgTop.bounds.height
        let w = self.bgTop.bounds.width
        path.move(to: CGPoint(x:0, y: h - 16))
        path.addLine(to: CGPoint(x:0, y:h))
        path.addLine(to: CGPoint(x:w, y:h))
        path.addLine(to: CGPoint(x:w, y: h - 16))
        path.addQuadCurve(to: CGPoint(x:0, y: h - 16), controlPoint:CGPoint(x:w / 2, y: h - 56))
        layer.path = path.cgPath
        layer.fillColor = UIColor.white.cgColor
        self.bgTop.layer.addSublayer(layer)
    }
    
    
    @IBAction func actionForPictrue(_ sender: UIButton) {
        if APP.user.id == "去登录"{
            let vc = KXLoginViewController()
            vc.isLogin = true
            self.push(vc, true)
            return
        }
        weak var weakself = self
        weakself?.sheet(nil, nil, ["相机","相簿"], { index, sheetTitle in
            DispatchQueue.main.async {
                Toast.startHud()
            }
            let  vc = UIImagePickerController()
            vc.delegate = self
            vc.allowsEditing = true
            vc.sourceType = index == 0 ? .camera : .photoLibrary
            vc.modalPresentationStyle = .overFullScreen
            weakself?.present(vc, animated: true, completion: {
                Toast.stopHud()
            })
        })
    }
}

//MARK: - UIImagePickerControllerDelegate / UINavigationControllerDelegate
extension KXMeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated:true, completion:nil)
    }
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        let img : UIImage = info[.editedImage] as! UIImage
        let data = img.jpegData(compressionQuality: 0.5)
        weak var weakself = self
        network.upload(KXConst.api_upload, para: nil, data:data!) { session, progress in
            
        } success: { response in
            let res = response as! NSDictionary
            let code = "\(res.value(forKey:"code")!)".intValue()
            let str = code == 0 ? LS("上传成功") : LS("上传失败")
            if code == 0{
                let url = res.value(forKey:"data") as! String
                let dict = ["url":url]
                Toast.msg(str)
                network.get(KXConst.api_updateAvatat, para:dict, header: nil) { reponse in
                    APP.user.headImg = url
                    APP.user.bg_saveOrUpdate()
                    weakself?.avatar.image = img
                    UIImage.withURL(APP.user.headImg , { img in
                        weakself!.avatar.image = img
                    })
                } fail: { error in }
            }
        } fail: { error in}
        picker.dismiss(animated:false, completion: {
            Toast.startHud(LS("上传图片中..."))
        })
    }
}

extension KXMeViewController{
    override func addNotify() {
        NotifyTool.add(self, #selector(updateUser), NotifyName.updateUser)
    }
    
    @objc func updateUser(){
        self.viewDidLoad()
    }
}

//MARK: - UITableViewDataSource
extension KXMeViewController : UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.array.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let dict = self.array[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: KXMeCell.ID()) as! KXMeCell
        cell.img.image = UIImage(named: dict["img"]!)
        cell.title.text = LS(dict["title"]!)
        return cell
    }
}
//MARK: - UITableViewDelegate
extension KXMeViewController : UITableViewDelegate{
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let dict = self.array[indexPath.row]
        let title = dict["title"]
        switch (title){
        case ("类别管理"):
            let vc = KXTypeViewController()
            self.push(vc, true)
        case ("隐私政策"):
            let vc = KXWebViewController()
            self.push(vc, true)
        case ("账号管理"):
            if APP.user.id == "去登录"{
                self.alert("提示", "您还未登录，是否前去登录？") { } _: {
                    self.actionForPictrue(UIButton())
                }
                return
            }
            let vc = KXAccountViewController()
            self.push(vc, true)
        default:
            break
        }
    }
}
